package org.jetnuke.modules.admin.stories;

import org.apache.log4j.Logger;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jforum.ActionServletRequest;
import net.jforum.JForumExecutionContext;
import net.jforum.util.preferences.ConfigKeys;
import net.jforum.util.preferences.SystemGlobals;

import net.jforum.util.legacy.commons.fileupload.FileItem;
import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.util.JetUtil;
import org.jetnuke.util.StringUtils;

public class UploadNewsFile implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(UploadNewsFile.class);

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (ai == null || ai.isSuperUser() == false)
			return null;

		ActionServletRequest asr = JForumExecutionContext.getRequest();
		FileItem file = (FileItem) asr.getObjectParameter("file");

		BufferedInputStream inputStream = new BufferedInputStream(file
				.getInputStream());

		String realName = file.getName();
		String simplifiedName = StringUtils.getSimpleFileName(realName);
		String dir = SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_STORE_DIR)
				+ "/news/";
		new File(dir).mkdirs();

		File f = new File(dir, simplifiedName);
		OutputStream outputStream = new BufferedOutputStream(
				new FileOutputStream(f));
		byte[] b = new byte[2048];
		while ((inputStream.read(b)) != -1) {
			outputStream.write(b);
		}

		outputStream.flush();
		outputStream.close();
		inputStream.close();
		JetUtil.redirect(vc, response, request.getContextPath()
				+ "/do/admin/uploaded");

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

}
